package com.zpz.framework.zpzoauth.common.dao;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;
/**
 * 数据源配置
 * @author: zhangpanzhi
 * @createDate: 2021/1/28 10:18
 */
@Configuration
@MapperScan(basePackages = "com.zpz.framework.zpzoauth.dao", sqlSessionFactoryRef = "oauthSqlSessionFactory")
public class OauthDataSourceConfig {
    /**
     * 表示这个数据源是默认数据源, 这个注解必须要加，因为不加的话spring将分不清楚那个为主数据源（默认数据源）
     * (prefix = "spring.datasource.oauth") 读取application.yml中的配置参数映射成为一个对象
     * @name: getOauthDataSource
     * @author: zhangpanzhi
     * @createDate: 2021/1/28 10:18
     * @param
     * @return: javax.sql.DataSource
     * @throws:
     */
    @Primary
    @Bean("oauthDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.oauth")
    public DataSource getOauthDataSource(){
        System.out.println("--------------生产oauthDataSource----Bean");
        return DruidDataSourceBuilder.create().build();
    }

    @Primary
    @Bean("oauthSqlSessionFactory")
    public SqlSessionFactory oauthSqlSessionFactory(@Qualifier("oauthDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        // mapper的xml形式文件位置必须要配置，不然将报错：no statement （这种错误也可能是mapper的xml中，namespace与项目的路径不一致导致）
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*.xml"));
        System.out.println("--------------生产oauthSqlSessionFactory----Bean");
        return bean.getObject();
    }

    @Primary
    @Bean("oauthSqlSessionTemplate")
    public SqlSessionTemplate oauthSqlSessionTemplate(@Qualifier("oauthSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        System.out.println("--------------生产oauthSqlSessionTemplate----Bean");
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
